package org.store.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.store.domain.User;
import org.store.mapper.UserMapper;
import org.store.service.UserService;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    QueryWrapper<User> wrapper = new QueryWrapper<>();

    @Override
    public User login(User user) {
        wrapper.clear();
        User searchingUser = null;
        //先匹配用户名
        wrapper.eq("username",user.getUsername());
        searchingUser = getOne(wrapper);
        if(searchingUser == null){
            //匹配失败，再匹配邮箱
            wrapper.clear();
            wrapper.eq("email",user.getEmail());
            searchingUser = getOne(wrapper);
            if(searchingUser == null){
                //匹配失败
                return null;
            }else {
                //匹配成功，验证密码是否正确
                if(user.getPassword().equals(searchingUser.getPassword()))return searchingUser;
                else return null;
            }
        }else {
            //匹配成功，验证密码是否正确
            if(user.getPassword().equals(searchingUser.getPassword()))return searchingUser;
            else return null;
        }
    }

    @Override
    public boolean register(User user) {
        if(checkUsername(user.getUsername()) && checkEmail(user.getEmail())){
            return save(user);
        }else return false;
    }

    public boolean checkUsername(String username){
        wrapper.clear();
        wrapper.eq("username",username);
        if(getOne(wrapper) == null)return true;
        else return false;
    }

    public boolean checkEmail(String email){
        wrapper.clear();
        wrapper.eq("email",email);
        if(getOne(wrapper) == null)return true;
        else return false;
    }
}
